package com.summerbird.mallchat.common.common.event.listener;

import com.summerbird.mallchat.common.common.event.UserBlackEvent;
import com.summerbird.mallchat.common.common.event.UserOnlineEvent;
import com.summerbird.mallchat.common.user.dao.UserDao;
import com.summerbird.mallchat.common.user.domain.entity.User;
import com.summerbird.mallchat.common.user.domain.enums.UserActiveStatusEnum;
import com.summerbird.mallchat.common.user.service.IpService;
import com.summerbird.mallchat.common.user.service.cache.UserCache;
import com.summerbird.mallchat.common.websocket.domain.vo.response.WSBaseResp;
import com.summerbird.mallchat.common.websocket.service.WebSocketService;
import com.summerbird.mallchat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Date;

@Component
public class UserBlackListener {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCache userCache;
    @Autowired
    private WebSocketService webSocketService;

    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void sendMsg(UserBlackEvent event){
        User user = event.getUser();
        // 通知其它用户，该用户已被拉入黑名单
        webSocketService.sendMsgToAll(WebSocketAdapter.buildBlack(user), user.getId());
    }

    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void changeUserStatus(UserBlackEvent event){
        User user = event.getUser();
        // 设置用户拉黑状态
        userDao.updateStatus(user.getId());
    }

    /**
     * 禁用某个用户后，清除黑名单缓存
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void clearCache(UserBlackEvent event){
        userCache.evictBlackMap();
    }

}
